<template>
  <div style="width: 100%; height: 400px;">
    <amap
      cache-key="map"
      ref="map"
      view-mode="3D"
      async
      :zoom.sync="zoom"
      :center.sync="center"
      :pitch.sync="pitch"
      :rotation.sync="rotation"
      :show-indoor-map="false"
      is-hotspot
      @click="mapClick"
      @hotspotclick="onHotspotClick"
    >
      <!-- :label="{
            content: '标记物提示!',
            direction: 'bottom',
          }" -->
      <amap-marker
        ref="marker"
        :position="position"
        draggable
        @dragend="dragend"
      />
    </amap>
  </div>
</template>

<script>
// 组件
// import Amap from '@amap/amap-vue/lib/amap';
// import AmapMarker from '@amap/amap-vue/lib/marker';
// 函数api
import { loadAmap } from "@amap/amap-vue";

export default {
  components: {
    // Amap,
    // AmapMarker,
  },
  data() {
    return {
      center: [116.473778, 39.990661],
      position: [116.473778, 39.990661],
      zoom: 14,
      pitch: 49, // 倾斜
      rotation: 15, // 旋转
      AMap: null,
    };
  },
  async mounted() {
    this.AMap = await loadAmap();
  },

  methods: {
    initLocation(city = "", address) {
      let geocoder = new this.AMap.Geocoder({
        city: city, //默认：“全国”
      });

      address = address ? city + address : city;
      geocoder.getLocation(address, (status, result) => {
        if (status === "complete" && result.geocodes.length) {
          let lnglat = result.geocodes[0].location;
          this.position = [lnglat.lng, lnglat.lat];
          this.center = [lnglat.lng, lnglat.lat];
          // 坐标更新事件
        } else {
          console.log("根据地址查询位置失败");
          // 失败提示事件
        }
      });
    },
    dragend(e) {
      console.log(e.lnglat.lng, e.lnglat.lat);
      this.initLocation("河北省唐山市");
      // 坐标更新事件
    },
    mapClick(e) {
      if (e && e.lnglat) {
        this.position = [e.lnglat.lng, e.lnglat.lat];
        this.center = [e.lnglat.lng, e.lnglat.lat];
      }
      // 坐标更新事件
    },
    onHotspotClick(e) {
      if (e && e.lnglat) {
        this.center = [e.lnglat.lng, e.lnglat.lat];
      }
    },
  },
};
</script>
